package com.Rsonly.spring.cloud.weather.service;

import com.Rsonly.spring.cloud.weather.vo.WeatherResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author 34234
 */
@Service
public class WeatherDataServiceImpl implements WeatherDataService {

    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(WeatherDataServiceImpl.class);

    private static final String WEATHER_URL = "http://wthrcdn.etouch.cn/weather_mini?";

    private static final int SUCCESS_CODE = 200;

    /**
     * redis数据过期时间
     */
    private static final long TIME_OUT = 1800L;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 根据城市id查询天气数据
     *
     * @param cityid
     * @return
     */
    @Override
    public WeatherResponse getDataByCityId(String cityid) {
        String url = WEATHER_URL + "citykey=" + cityid;
        return this.doGetWeather(url);
    }

    /**
     * 根据城市名称查询天气数据
     *
     * @param cityName
     * @return
     */
    @Override
    public WeatherResponse getDataByCityName(String cityName) {
        String url = WEATHER_URL + "city=" + cityName;
        return this.doGetWeather(url);
    }


    private WeatherResponse doGetWeather(String url) {

        String key = url;
        String strBody = null;
        WeatherResponse weatherResponse = null;
        ObjectMapper mapper = new ObjectMapper();
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        //先查缓存，缓存中有就取用缓存数据
        if (stringRedisTemplate.hasKey(key)) {
            LOGGER.info("Redis has data");
            strBody = ops.get(key);
        } else {
            LOGGER.info("Redis hasn't data");
            //缓存没有，再调用服务接口获取数据
            ResponseEntity<String> responseString = restTemplate.getForEntity(url, String.class);
            if (responseString.getStatusCodeValue() == SUCCESS_CODE) {
                strBody = responseString.getBody();
            }
            //数据写入缓存
            ops.set(key, strBody, TIME_OUT, TimeUnit.SECONDS);
        }
        try {
            weatherResponse = mapper.readValue(strBody, WeatherResponse.class);
        } catch (IOException e) {
            LOGGER.error("Redis has error", e);
        }
        return weatherResponse;
    }

    /**
     * 根据城市id同步天气
     *
     * @param cityId
     */
    @Override
    public void syncDataByCityId(String cityId) {
        String url = WEATHER_URL + "citykey=" + cityId;
        this.saveWeatherData(url);
    }

    /**
     * 把天气数据放入缓存
     *
     * @param url
     */
    private void saveWeatherData(String url) {
        String key = url;
        String strBody = null;

        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();


        //缓存没有，再调用服务接口获取数据
        ResponseEntity<String> responseString = restTemplate.getForEntity(url, String.class);
        if (responseString.getStatusCodeValue() == SUCCESS_CODE) {
            strBody = responseString.getBody();
        }
        //数据写入缓存
        ops.set(key, strBody, TIME_OUT, TimeUnit.SECONDS);

    }
}
